package com.iwomy.envpro.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.iwomy.envpro.admin.api.dto.UserInfo;
import com.iwomy.envpro.admin.api.entity.SysTenant;
import com.iwomy.envpro.admin.api.entity.SysUser;
import com.iwomy.envpro.admin.api.feign.RemoteTenantService;
import com.iwomy.envpro.admin.api.feign.RemoteUserService;
import com.iwomy.envpro.app.api.dto.AppUserInfo;
import com.iwomy.envpro.app.api.entity.AppUser;
import com.iwomy.envpro.app.api.feign.RemoteAppUserService;
import com.iwomy.envpro.common.core.constant.SecurityConstants;
import com.iwomy.envpro.common.core.util.R;
import com.iwomy.envpro.common.data.datascope.DataScope;
import com.iwomy.envpro.common.data.tenant.TenantContextHolder;
import com.iwomy.envpro.platform.constant.*;
import com.iwomy.envpro.platform.dto.DeviceDataDTO;
import com.iwomy.envpro.platform.entity.*;
import com.iwomy.envpro.platform.service.*;
import com.iwomy.envpro.platform.utils.AIOTUtils;
import com.iwomy.envpro.platform.utils.DescribeInstances;
import com.iwomy.envpro.platform.utils.JsonUtil;
import com.iwomy.envpro.platform.utils.RedisClient;
import com.tencentcloudapi.vms.v20200902.models.SendTtsVoiceResponse;
import lombok.extern.slf4j.Slf4j;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.dromara.sms4j.provider.service.AbstractSmsBlend;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;


/**
 * 设备上报数据
 *
 * @author pig
 * @date 2023-08-31 09:28:08
 */
@Service
@Slf4j
public class DeviceServiceImpl implements DeviceService {
	@Resource
	private MongoTemplate mongoTemplate;
	@Resource
	private AirMonitorEquipmentService airMonitorEquipmentService;
	@Resource
	private AirSiteService airSiteService;
	@Resource
	private RedisClient redisClient;
	@Resource
	private AlarmLoggingService alarmLoggingService;
	@Resource
	private BasicTriggerService basicTriggerService;
	@Resource
	private BasicSmsConfigService basicSmsConfigService;
	@Resource
	private BasicTelephoneConfigService basicTelephoneConfigService;
	@Resource
	private AirGridMemberService airGridMemberService;
	@Resource
	private RemoteTenantService remoteTenantService;
	@Resource
	private RemoteUserService remoteUserService;
	@Resource
	private PlatformSmsConfigService platformSmsConfigService;
	@Resource
	private PlatformTelephoneConfigService platformTelephoneConfigService;
	@Resource
	private MpService mpService;
	//	@Resource
//	private RemoteAppUserService remoteAppUserService;
	@Resource
	private BasicNotificationRecordService basicNotificationRecordService;
	@Resource
	private TelecomTianyiAiotService telecomTianyiAiotService;


	@Override
	public void escalation(DeviceDataDTO deviceDataDTO, TpEnum tpEnum) {
		String mn = deviceDataDTO.getMn();
		if (StrUtil.isEmpty(mn)) {
			log.error("escalation mn is empty : {}", JSONObject.toJSONString(deviceDataDTO));
			return;
		}
		AirRealTimeDataEntity airRealTimeDataEntity = updateDeviceOnline(mn);

		this.updateRealTimeDate(deviceDataDTO, airRealTimeDataEntity, tpEnum);

	}

	@Override
	public void deviceOnline(String mn, Integer status) {
		if (StrUtil.isEmpty(mn)) return;
		AirMonitorEquipmentEntity airMonitorEquipmentEntity = airMonitorEquipmentService.selectOneByEquipmentId(mn);
		if (ObjectUtil.isNull(airMonitorEquipmentEntity)) return;
		airMonitorEquipmentEntity.setStatus(status);
		airMonitorEquipmentService.updateById(airMonitorEquipmentEntity);
	}


	/**
	 * 更新设备的在线情况
	 *
	 * @param mn
	 */
	private AirRealTimeDataEntity updateDeviceOnline(String mn) {
//		String key = RedisConstants.ENVPRO_DEVICS_KEY + mn;
//		if (redisClient.expire(key, RedisConstants.ENVPRO_DEVICE_EXPIRE)) {
//			return redisClient.get(key, AirRealTimeDataEntity.class);
//		}
		TenantContextHolder.setTenantSkip();
		//不存在则更新 设备在线状态
		AirMonitorEquipmentEntity airMonitorEquipment = airMonitorEquipmentService.selectOneByEquipmentId(mn);
		if (ObjectUtil.isNull(airMonitorEquipment)) {
			log.error("{}设备不存在", mn);
			return null;
		}
		airMonitorEquipment.setStatus(2);
		airMonitorEquipmentService.updateById(airMonitorEquipment);

		AirSiteEntity airSite = airSiteService.getById(airMonitorEquipment.getAirSiteId());
		if (ObjectUtil.isNull(airSite)) {
			return null;
		}
		//保存站点信息、设备信息
		AirRealTimeDataEntity airRealTimeDataEntity = new AirRealTimeDataEntity();
		airRealTimeDataEntity.setSiteId(airSite.getId());
		airRealTimeDataEntity.setAreaName(airSite.getAreaName());
		airRealTimeDataEntity.setAreaId(airSite.getAreaId());
		airRealTimeDataEntity.setLatitude(airSite.getLatitude());
		airRealTimeDataEntity.setLongitude(airSite.getLongitude());
		airRealTimeDataEntity.setMonitorEquipmentId(airMonitorEquipment.getId());
		airRealTimeDataEntity.setName(airMonitorEquipment.getName());


//		redisClient.set(key, JSONObject.toJSONString(airRealTimeDataEntity), RedisConstants.ENVPRO_DEVICE_EXPIRE);
		return airRealTimeDataEntity;

	}

	/**
	 * 插入实时数据
	 *
	 * @param deviceDataDTO         上报的数据
	 * @param airRealTimeDataEntity 设备以及站点信息
	 * @param tpEnum                数据类型
	 */
	private void updateRealTimeDate(DeviceDataDTO deviceDataDTO, AirRealTimeDataEntity airRealTimeDataEntity, TpEnum tpEnum) {
		if (ObjectUtil.isNull(airRealTimeDataEntity)) return;


		//新增动态
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("recordTime", LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
		jsonObject.put("siteId", airRealTimeDataEntity.getSiteId());
		jsonObject.put("monitorEquipmentId", airRealTimeDataEntity.getMonitorEquipmentId());
		jsonObject.putAll(deviceDataDTO.getCp());


		mongoTemplate.insert(jsonObject, tpEnum.getName());

		//todo 判断是否报警,如果有影响改成异步
		AirMonitorEquipmentEntity airMonitorEquipment = airMonitorEquipmentService.selectOneByEquipmentId(deviceDataDTO.getMn());

		//记录时间
		airMonitorEquipment.setRecordTime(LocalDateTime.now());
		airMonitorEquipmentService.updateById(airMonitorEquipment);

		TelecomTianyiAiotEntity telecomTianyiAiotEntity = telecomTianyiAiotService.oneByImei(deviceDataDTO.getMn());
		try {
			AIOTUtils.report(telecomTianyiAiotEntity, deviceDataDTO);
		} catch (Exception e) {
			log.error("天翼AIOT上传失败:", e.getMessage());
		}

		judgeAllTriggers(deviceDataDTO, airMonitorEquipment);
	}

	private void judgeAllTriggers(DeviceDataDTO deviceDataDTO, AirMonitorEquipmentEntity airMonitorEquipment) {
		//查看模板是否启用
		LambdaQueryWrapper<BasicTriggerEntity> wrapper = Wrappers.<BasicTriggerEntity>lambdaQuery().eq(BasicTriggerEntity::getDataTemplateId, airMonitorEquipment.getDataTemplateId()).eq(BasicTriggerEntity::getStatus, 2);
		List<BasicTriggerEntity> list = basicTriggerService.list(wrapper);

		if (ObjectUtil.isEmpty(list) || list.size() < 1) return;
		//查看触发器
		for (BasicTriggerEntity basicTriggerEntity : list) {
			BigDecimal cpRtd = deviceDataDTO.getCpRtd(basicTriggerEntity.getFactorCode());
			judgmentExpression(airMonitorEquipment, basicTriggerEntity, cpRtd);
		}

	}


	private void judgmentExpression(AirMonitorEquipmentEntity airMonitorEquipment, BasicTriggerEntity basicTriggerEntity, BigDecimal cpRtd) {
		if (ObjectUtil.isNull(cpRtd)) return;
		Integer triggerConditions = basicTriggerEntity.getTriggerConditions();
		BigDecimal aValue = basicTriggerEntity.getTriggerConditionsVala().stripTrailingZeros();
		BigDecimal bValue = basicTriggerEntity.getTriggerConditionsValb().stripTrailingZeros();
		String alarmCauses;
		switch (triggerConditions) {
			case TriggerConditionConstants.VALUE_IS_LOWER_THAN_A_CODE:  // 数值低于A
				if (cpRtd.compareTo(aValue) < 0) {
					alarmCauses = String.format(TriggerConditionConstants.VALUE_IS_LOWER_THAN_A_CONTENT, aValue.toPlainString());
					break;

				}
				return;
			case TriggerConditionConstants.VALUE_IS_HIGHER_THAN_B_CODE: // 数值高于B
				if (cpRtd.compareTo(bValue) > 0) {
					alarmCauses = String.format(TriggerConditionConstants.VALUE_IS_HIGHER_THAN_B_CONTENT, bValue.toPlainString());
					break;
				}
				return;
			case TriggerConditionConstants.VALUE_IS_BETWEEN_AB_CODE: // 数值介于AB之间
				if (cpRtd.compareTo(aValue) > 0 && cpRtd.compareTo(bValue) < 0) {
					alarmCauses = String.format(TriggerConditionConstants.VALUE_IS_BETWEEN_AB_CONTENT, aValue.toPlainString(), bValue.toPlainString());
					break;
				}
				return;
			case TriggerConditionConstants.VALUE_HIGHER_THAN_B_LOWER_THAN_A_CODE: // 数值高于B低于A
				if (cpRtd.compareTo(bValue) > 0 || cpRtd.compareTo(aValue) < 0) {
					alarmCauses = String.format(TriggerConditionConstants.VALUE_HIGHER_THAN_B_LOWER_THAN_A_CONTENT, bValue.toPlainString(), aValue.toPlainString());
					break;
				}
				return;
			case TriggerConditionConstants.VALUE_IS_EQUAL_A_CODE: // 数值等于A
				if (cpRtd.compareTo(aValue) == 0) {
					alarmCauses = String.format(TriggerConditionConstants.VALUE_IS_EQUAL_A_CONTENT, aValue.toPlainString());
					break;
				}
				return;
			default:
				return;
		}
		//跳过多住户
		TenantContextHolder.clear();
		AlarmLoggingEntity alarmLoggingEntity = new AlarmLoggingEntity();
		alarmLoggingEntity.setAlarmCauses(String.format("%s当前值:%s,%s", basicTriggerEntity.getFactorName(), cpRtd, alarmCauses));
		alarmLoggingEntity.setEquipmentId(airMonitorEquipment.getId());
		alarmLoggingEntity.setEquipmentName(airMonitorEquipment.getName());
		alarmLoggingEntity.setEquipmentCode(airMonitorEquipment.getEquipmentCode());
		alarmLoggingEntity.setCurrentValue(cpRtd);
		alarmLoggingEntity.setFactorId(basicTriggerEntity.getFactorId());
		alarmLoggingEntity.setFactorCode(basicTriggerEntity.getFactorCode());
		alarmLoggingEntity.setCnName(basicTriggerEntity.getFactorName());
		alarmLoggingEntity.setTenantId(airMonitorEquipment.getTenantId());
		alarmLoggingEntity.setUpdateBy(basicTriggerEntity.getUpdateBy());
		alarmLoggingEntity.setSiteId(airMonitorEquipment.getAirSiteId());
		alarmLoggingEntity.setAlarmType(10);
		alarmLoggingEntity.setDeptId(airMonitorEquipment.getDeptId());
		alarmLoggingService.save(alarmLoggingEntity);

		AirMonitorEquipmentEntity airMonitorEquipmentEntity = new AirMonitorEquipmentEntity();
		airMonitorEquipmentEntity.setId(airMonitorEquipment.getId());
		airMonitorEquipmentEntity.setAlarmStatus(DeviceStatusConstants.ABNORMAL);
		airMonitorEquipmentEntity.setUpdateBy(airMonitorEquipment.getUpdateBy());
		airMonitorEquipmentService.updateById(airMonitorEquipmentEntity);
		this.smsAlarm(basicTriggerEntity, airMonitorEquipment, alarmCauses, cpRtd);
		this.telephoneAlarm(basicTriggerEntity, airMonitorEquipment, alarmLoggingEntity);
		this.mpMsg(basicTriggerEntity, airMonitorEquipment, alarmLoggingEntity);


	}

	/**
	 * 短信报警
	 *
	 * @param basicTriggerEntity
	 * @param airMonitorEquipment
	 * @param alarmCauses
	 * @param cpRtd
	 */
	private void smsAlarm(BasicTriggerEntity basicTriggerEntity, AirMonitorEquipmentEntity airMonitorEquipment
			, String alarmCauses, BigDecimal cpRtd) {
		if (basicTriggerEntity.getSmsAlarm() != 20) return;


		//平台每月剩余的时长

		BasicNotificationRecordEntity basicNotificationRecordEntity = new BasicNotificationRecordEntity();
		TenantContextHolder.setTenantId(airMonitorEquipment.getTenantId());
		BasicSmsConfigEntity smsConfig = this.getSmsConfig(basicNotificationRecordEntity, airMonitorEquipment.getTenantId());


		if (ObjectUtil.isNull(smsConfig)) {
			log.error("短信消息:参数未配置");
			return;
		}
		if (!redisClient.tryLock("alarm:sms:" + airMonitorEquipment.getId(), alarmCauses, smsConfig.getIntervalTime() * 60)) {
			log.error("短信消息:间隔时间{}分钟", smsConfig.getIntervalTime());
			return;
		}
		basicNotificationRecordEntity.setSupplier(smsConfig.getSupplier());
		AirGridMemberEntity gridMember = airGridMemberService.getById(airMonitorEquipment.getGridMemberId());
		String phone = gridMember.getPhone();
		basicNotificationRecordEntity.setReceiver(phone);
		basicNotificationRecordEntity.setReceiverName(gridMember.getName());
		AbstractSmsBlend smsBlend = basicSmsConfigService.getSmsBlend(smsConfig);
		String body = airMonitorEquipment.getEquipmentCode() + "&" + basicTriggerEntity.getFactorName()
				+ "&" + cpRtd.toPlainString() + "&" + alarmCauses;
		basicNotificationRecordEntity.setRequestContent(body);

		SmsResponse smsResponse = smsBlend.sendMessage(phone, body);
		log.info("短信消息:sendMessage,phone:{},body:{},smsResponse:{}", phone, body, JSONObject.toJSONString(smsResponse));
		basicNotificationRecordEntity.setResponseContent(JSONObject.toJSONString(smsResponse));
		if (smsResponse.isSuccess()) {

			basicNotificationRecordEntity.setSendResults(NotificationRecordConstants.NOTIFICATION_RECORD_SEND_RESULTS_SUCCESS);


//			String serialNo = JSONObject.parseObject(smsResponse.getData().toString()).getJSONObject("Response")
//					.getJSONArray("SendStatusSet").getJSONObject(0).getString("SerialNo");
			String serialNo = (String) JsonUtil.
					getValueByKey(JSONObject.parseObject(smsResponse.getData().toString()), "SerialNo").get(0);
			basicNotificationRecordEntity.setSupplierIdentifying(serialNo);

		} else {
			basicNotificationRecordEntity.setSendResults(NotificationRecordConstants.NOTIFICATION_RECORD_SEND_RESULTS_FAIL);
		}
		basicNotificationRecordService.save(basicNotificationRecordEntity);

	}


	/**
	 * 语音报警
	 *
	 * @param basicTriggerEntity
	 * @param airMonitorEquipment
	 * @param alarmLoggingEntity
	 */
	private void telephoneAlarm(BasicTriggerEntity basicTriggerEntity, AirMonitorEquipmentEntity airMonitorEquipment, AlarmLoggingEntity alarmLoggingEntity) {

		if (basicTriggerEntity.getTelephoneAlarm() != 20) return;


		BasicNotificationRecordEntity basicNotificationRecordEntity = new BasicNotificationRecordEntity();
		TenantContextHolder.setTenantId(airMonitorEquipment.getTenantId());
		BasicTelephoneConfigEntity telephoneConfig = this.getTelephoneConfig(basicNotificationRecordEntity, airMonitorEquipment.getTenantId());

		if (ObjectUtil.isNull(telephoneConfig)) {
			log.error("语音消息:参数未配置");
			return;
		}

		//平台每月剩余的时长
		if (!redisClient.tryLock("alarm:telephone:" + airMonitorEquipment.getId(), alarmLoggingEntity.getAlarmCauses(), telephoneConfig.getIntervalTime() * 60)) {
			log.error("语音消息:间隔时间{}分钟", telephoneConfig.getIntervalTime());
			return;
		}
		AirGridMemberEntity gridMember = airGridMemberService.getById(airMonitorEquipment.getGridMemberId());
		String phone = gridMember.getPhone();
		basicNotificationRecordEntity.setReceiver(phone);
		basicNotificationRecordEntity.setReceiverName(gridMember.getName());
		String[] templateParamSet = {airMonitorEquipment.getAddress(), airMonitorEquipment.getEquipmentCode(), alarmLoggingEntity.getAlarmCauses()};
		log.info("语音消息:发送内容{}", StrUtil.join(",", templateParamSet));
		basicNotificationRecordEntity.setSupplier(telephoneConfig.getSupplier());
		try {
			basicNotificationRecordEntity.setRequestContent(StrUtil.join(",", templateParamSet));
			SendTtsVoiceResponse sendTtsVoiceResponse = DescribeInstances.sendTelephone(telephoneConfig, phone, templateParamSet);
			basicNotificationRecordEntity.setResponseContent(SendTtsVoiceResponse.toJsonString(sendTtsVoiceResponse));
			basicNotificationRecordEntity
					.setSendResults(NotificationRecordConstants.NOTIFICATION_RECORD_SEND_RESULTS_SUCCESS);
			basicNotificationRecordEntity.setSupplierIdentifying(sendTtsVoiceResponse.getSendStatus().getCallId());
		} catch (Exception e) {
			basicNotificationRecordEntity
					.setSendResults(NotificationRecordConstants.NOTIFICATION_RECORD_SEND_RESULTS_FAIL);
			basicNotificationRecordEntity.setResponseContent(e.getMessage());
			log.error("语音消息:{}", e.getMessage());
		} finally {
			basicNotificationRecordService.save(basicNotificationRecordEntity);

		}
	}

	/**
	 * 获取短信配置
	 *
	 * @param basicNotificationRecordEntity
	 * @return
	 */
	private BasicSmsConfigEntity getSmsConfig(BasicNotificationRecordEntity basicNotificationRecordEntity, Long tenantId) {
		basicNotificationRecordEntity.setTenantId(tenantId);
		basicNotificationRecordEntity.setConsumeType(NotificationRecordConstants.NOTIFICATION_RECORD_CONSUME_CUSTOM);
		basicNotificationRecordEntity.setNotificationType(NotificationRecordConstants.NOTIFICATION_RECORD_TYPE_SMS);
		BasicSmsConfigEntity one = basicSmsConfigService.getOne(Wrappers.<BasicSmsConfigEntity>lambdaQuery()
				.eq(BasicSmsConfigEntity::getStatus, 20));

		if (ObjectUtil.isNotNull(one)) return one;
		//使用平台短信配置
		R<SysTenant> details = remoteTenantService.details(tenantId, SecurityConstants.FROM_IN);
		SysTenant sysTenant = details.getData();
		Integer residueTime = Optional.ofNullable(sysTenant.getSmgTotal() - sysTenant.getUsedSms()).orElse(0);
		log.info("短信剩余条数:{}", residueTime);
		if (residueTime <= 0) return one;
		List<PlatformSmsConfigEntity> list = platformSmsConfigService.list();
		PlatformSmsConfigEntity platformSmsConfigEntity = Optional.ofNullable(list.get(0)).orElse(null);

		if (ObjectUtil.isNull(platformSmsConfigEntity)) return one;

		one = BeanUtil.copyProperties(platformSmsConfigEntity, BasicSmsConfigEntity.class);
		basicNotificationRecordEntity.setConsumeType(NotificationRecordConstants.NOTIFICATION_RECORD_CONSUME_PLATFORM);
		return one;
	}

	/**
	 * 获取语音配置
	 *
	 * @param basicNotificationRecordEntity
	 * @param tenantId
	 * @return
	 */
	private BasicTelephoneConfigEntity getTelephoneConfig(BasicNotificationRecordEntity basicNotificationRecordEntity, Long tenantId) {
		BasicTelephoneConfigEntity one = basicTelephoneConfigService.getOne(Wrappers.<BasicTelephoneConfigEntity>lambdaQuery()
				.eq(BasicTelephoneConfigEntity::getStatus, 20));
		basicNotificationRecordEntity.setNotificationType(NotificationRecordConstants.NOTIFICATION_RECORD_TYPE_TELEPHONE);
		basicNotificationRecordEntity.setConsumeType(NotificationRecordConstants.NOTIFICATION_RECORD_CONSUME_CUSTOM);
		basicNotificationRecordEntity.setTenantId(tenantId);


		if (ObjectUtil.isNotNull(one)) return one;

		R<SysTenant> details = remoteTenantService.details(tenantId, SecurityConstants.FROM_IN);
		SysTenant sysTenant = details.getData();
		Integer residueTime = Optional.ofNullable(sysTenant.getVoiceTotal() - sysTenant.getUsedVoice()).orElse(0);
		log.info("语音剩余时长:{}", residueTime);
		if (residueTime <= 0)
			return one;
		List<PlatformTelephoneConfigEntity> list = platformTelephoneConfigService.list();
		PlatformTelephoneConfigEntity platformTelephoneConfigEntity = Optional.ofNullable(list.get(0)).orElse(null);

		if (ObjectUtil.isNull(platformTelephoneConfigEntity))
			return one;

		one = BeanUtil.copyProperties(platformTelephoneConfigEntity, BasicTelephoneConfigEntity.class);

		basicNotificationRecordEntity.setConsumeType(NotificationRecordConstants.NOTIFICATION_RECORD_CONSUME_PLATFORM);

		return one;

	}


	/**
	 * 发送微信消息
	 *
	 * @param basicTriggerEntity
	 * @param airMonitorEquipment
	 * @param alarmLoggingEntity
	 */
	private void mpMsg(BasicTriggerEntity basicTriggerEntity, AirMonitorEquipmentEntity airMonitorEquipment, AlarmLoggingEntity alarmLoggingEntity) {

		if (basicTriggerEntity.getOfficialAccountAlarm() != 20) return;

		//不然调用接口查不到数据
		TenantContextHolder.setTenantId(airMonitorEquipment.getTenantId());

		AirGridMemberEntity gridMember = airGridMemberService.getById(airMonitorEquipment.getGridMemberId());

		R<UserInfo> info = remoteUserService.info(gridMember.getPhone(), SecurityConstants.FROM_IN);

		//		设备编号
		//		{{character_string11.DATA}}
		//		设备位置
		//		{{thing22.DATA}}
		//		告警时间
		//		{{time3.DATA}}
		//		异常原因
		//		{{thing25.DATA}}
		log.info("发送微信消息,phone:{},alarmCauses:{},info:{}", gridMember.getPhone(), alarmLoggingEntity.getAlarmCauses(), JSONObject.toJSONString(info));

		UserInfo userInfo = Optional.ofNullable(info.getData()).orElse(null);
		if (ObjectUtil.isNull(userInfo)) return;
		SysUser sysUser = userInfo.getSysUser();
		String wxOpenid = sysUser.getWxOpenid();

		Map map = new HashMap();
		//字数不能超过20字
		map.put("character_string11", airMonitorEquipment.getEquipmentCode());
		map.put("thing22", airMonitorEquipment.getAddress().substring(0, airMonitorEquipment.getAddress().length() > 20 ? 20 : airMonitorEquipment.getAddress().length()));
		map.put("time3", LocalDateTimeUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
//		map.put("thing25", alarmLoggingEntity.getAlarmCauses());
		map.put("thing25", alarmLoggingEntity.getAlarmCauses().substring(0, alarmLoggingEntity.getAlarmCauses().length() > 20 ? 20 : alarmLoggingEntity.getAlarmCauses().length()));
		String url = "https://mp.iwomy.com/#/pages/abnormalAlarm/detail?id=" + alarmLoggingEntity.getId();
		mpService.sendTemplateMsg(wxOpenid, gridMember.getName(), "aJfsrTR-1bf7bs_3LrR_ikll5eKS9T7F_hNsjMFgtFI", map, url);

	}
}